#include "thread_pool.h"
#include <unistd.h>

extern User users;

int delUser(int fd, int userid){
    UserNode* p = users.front;
    UserNode* after = NULL;
    while(p!=NULL){
        if(p->fd == fd && p->userid == userid){
            if(after==NULL){
                users.front = p->next;
            }else{
                after->next = p->next;
            }
            close(p->fd);
            free(p);
            return 0;
        }
        after = p;
        p = p->next;
    }
    return -1;
}

int addUser(int fd, int userid){
    UserNode *p1 = users.front;

    //查看原链表中是否已经存在该fd
    while(p1 && p1->fd != fd);
    if(p1){     //fd已存在
        p1->userid = userid;
        return 0;
    }

    //fd不存在，创建新节点并插入链表
    UserNode *node = (UserNode*)calloc(1, sizeof(UserNode));
    node->fd = fd;
    node->userid = userid;

    if(!users.front){
        node->next = NULL;
        users.front = users.rear = node;
    } else {
        users.rear->next = node;
        users.rear = node;
    }

    return 0;
    
}

int getUserid(int fd, int * userid){
    UserNode* p = users.front;
    while(p && p->fd != fd);
    if(!p) {
        return 1;
    }else{
        *userid = p->userid;
        return 0;
    }
}

int destroyUsers(){
    UserNode* p = users.front;
    while(p!=NULL){
        UserNode* temp = p;
        p = p->next;
        free(temp);
    }
    return 0;
}
